package com.example.fameex_update;

import static android.content.ContentValues.TAG;

//import static androidx.core.graphics.drawable.IconCompat.getResources;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.IntentSender;
import android.nfc.Tag;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import androidx.annotation.IdRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.google.android.gms.tasks.Task;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.play.core.appupdate.AppUpdateInfo;
import com.google.android.play.core.appupdate.AppUpdateManager;
import com.google.android.play.core.appupdate.AppUpdateManagerFactory;
import com.google.android.play.core.appupdate.AppUpdateOptions;
import com.google.android.play.core.common.IntentSenderForResultStarter;
import com.google.android.play.core.install.InstallStateUpdatedListener;
import com.google.android.play.core.install.model.AppUpdateType;
import com.google.android.play.core.install.model.InstallStatus;
import com.google.android.play.core.install.model.UpdateAvailability;

import java.util.logging.Logger;

import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result;

/**
 * FameexUpdatePlugin
 */
public class FameexUpdatePlugin implements FlutterPlugin, MethodCallHandler, Application.ActivityLifecycleCallbacks {
    private static final int MY_REQUEST_CODE = 9001;
    /// The MethodChannel that will the communication between Flutter and native Android
    ///
    /// This local reference serves to register the plugin with the Flutter Engine and unregister it
    /// when the Flutter Engine is detached from the Activity
    private MethodChannel channel;
    private Context mContext;
    private AppUpdateManager appUpdateManager;
    private Task<AppUpdateInfo> appUpdateInfoTask;
    private AppUpdateInfo mAppUpdateInfo;
    private Activity currentActivity;


    @Override
    public void onAttachedToEngine(@NonNull FlutterPluginBinding flutterPluginBinding) {
        mContext = flutterPluginBinding.getApplicationContext();
        channel = new MethodChannel(flutterPluginBinding.getBinaryMessenger(), "fameex_update");
        channel.setMethodCallHandler(this);
    }

    @Override
    public void onMethodCall(@NonNull MethodCall call, @NonNull Result result) {
        if (call.method.equals("getPlatformVersion")) {
            result.success("Android " + android.os.Build.VERSION.RELEASE);
        } else if (call.method.equals("checkGoogleUpdate")) {
            // 谷歌商店是否有更新
            checkGoogleUpdate(result);
        } else if (call.method.equals("startUpdate")) {
            // 开始更新
            startUpdate();
        } else {
            result.notImplemented();
        }
    }

    @Override
    public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {
        channel.setMethodCallHandler(null);
    }

    // 检查是否有可用更新
    public void checkGoogleUpdate(Result result) {
        appUpdateManager = AppUpdateManagerFactory.create(mContext);
        // Returns an intent object that you use to check for an update.
        appUpdateInfoTask = appUpdateManager.getAppUpdateInfo();
        // Checks that the platform will allow the specified type of update.
        appUpdateInfoTask.addOnSuccessListener(appUpdateInfo -> {
            mAppUpdateInfo = appUpdateInfo;
            if (appUpdateInfo.updateAvailability() == UpdateAvailability.UPDATE_AVAILABLE
                    // This example applies an immediate update. To apply a flexible update
                    // instead, pass in AppUpdateType.FLEXIBLE
                    && appUpdateInfo.isUpdateTypeAllowed(AppUpdateType.FLEXIBLE)) {
                // Request the update.
                result.success(true);
            } else {
                result.success(false);
            }
        });
    }

    @Override
    public void onActivityPostResumed(@NonNull Activity activity) {
        Application.ActivityLifecycleCallbacks.super.onActivityPostResumed(activity);


    }

    public void startUpdate() {
        try {
            Log.v("----------logv","添加监听");
            appUpdateManager.registerListener(listener);
            Log.v("----------logv","调用更新");

            boolean start =   appUpdateManager.startUpdateFlowForResult(
                    // Pass the intent that is returned by 'getAppUpdateInfo()'.
                    mAppUpdateInfo,
                    // Or 'AppUpdateType.FLEXIBLE' for flexible updates.
                    AppUpdateType.FLEXIBLE,
                    // The current activity making the update request.
                    currentActivity,
                    // Include a request code to later monitor this update request.
                    MY_REQUEST_CODE);
            // Before starting an update, register a listener for updates.



//         boolean start = appUpdateManager.startUpdateFlowForResult(
//                    // Pass the intent that is returned by 'getAppUpdateInfo()'.
//                    mAppUpdateInfo,
//                    // The current activity making the update request.
//                    currentActivity,
//                    // Or pass 'AppUpdateType.FLEXIBLE' to newBuilder() for
//                    // flexible updates.
//                    AppUpdateOptions.newBuilder(AppUpdateType.FLEXIBLE)
//                            .setAllowAssetPackDeletion(true)
//                            .build(),
//                    // Include a request code to later monitor this update request.
//                    MY_REQUEST_CODE);
            if (start) {
                Log.v("----------logv","开始更新调用成功");
            } else {
                Log.v("----------logv","开始更新调用失败");
            }
            Log.v("----------logv","调用更新完成");
// When status updates are no longer needed, unregister the listener.
//            appUpdateManager.unregisterListener(listener);

        } catch (IntentSender.SendIntentException e) {
            Log.v("----------logv","失败");
            Log.v("----------logv",e.getMessage());
            // 移除监听
            appUpdateManager.unregisterListener(listener);
            e.printStackTrace();
        }
    }


    // Create a listener to track request state updates.
    InstallStateUpdatedListener listener = state -> {
        // (Optional) Provide a download progress bar.
        Log.v("----------logv","开始监听");
        Log.v("----------logv",String.valueOf(state.installStatus()));
        if (state.installStatus() == InstallStatus.DOWNLOADING) {
            long bytesDownloaded = state.bytesDownloaded();
            long totalBytesToDownload = state.totalBytesToDownload();
            // Implement progress bar.

            Log.v("----------logv",String.valueOf(totalBytesToDownload));
            Log.v("----------logv",String.valueOf(bytesDownloaded));
        }  else if (state.installStatus() == InstallStatus.DOWNLOADED){
            Log.v("----------logv","下载完成");
            popupSnackbarForCompleteUpdate();
        }
        // Log state or install the update.
    };

    // Displays the snackbar notification and call to action.
    private void popupSnackbarForCompleteUpdate() {
        Snackbar snackbar =
                Snackbar.make(
                        findViewById(R.id.text),
                        "An update has just been downloaded.",
                        Snackbar.LENGTH_INDEFINITE);
        snackbar.setAction("RESTART", view -> appUpdateManager.completeUpdate());
//        snackbar.setActionTextColor(
//                getResources().getColor(R.color.snackbar_action_text_color));
        snackbar.show();
    }

    public View findViewById(@IdRes int id) {
        return currentActivity.getWindow().findViewById(id);
    }


//    InstallStateUpdatedListener listener = state -> {
//        if (state.installStatus() == InstallStatus.DOWNLOADED) {
//            // After the update is downloaded, show a notification
//            // and request user confirmation to restart the app.
//            popupSnackbarForCompleteUpdate();
//        }
//    };
//
//    // Displays the snackbar notification and call to action.
//    private void popupSnackbarForCompleteUpdate() {
//        Snackbar snackbar =
//                Snackbar.make(
//                        findViewById(R.id.activity_main_layout),
//                        "An update has just been downloaded.",
//                        Snackbar.LENGTH_INDEFINITE);
//        snackbar.setAction("RESTART", view -> appUpdateManager.completeUpdate());
//        snackbar.setActionTextColor(
//                getResources().getColor(R.color.snackbar_action_text_color));
//        snackbar.show();
//    }

    @Override
    public void onActivityCreated(@NonNull Activity activity, @Nullable Bundle bundle) {

    }

    @Override
    public void onActivityStarted(@NonNull Activity activity) {

    }

    @Override
    public void onActivityResumed(@NonNull Activity activity) {
        this.currentActivity = activity;
    }

    @Override
    public void onActivityPaused(@NonNull Activity activity) {
        this.currentActivity = null;
    }

    @Override
    public void onActivityStopped(@NonNull Activity activity) {

    }

    @Override
    public void onActivitySaveInstanceState(@NonNull Activity activity, @NonNull Bundle bundle) {

    }

    @Override
    public void onActivityDestroyed(@NonNull Activity activity) {

    }
}

